package com.cdvtc.flower.web.servlet;

import com.cdvtc.flower.dao.ProductsDao;
import com.cdvtc.flower.dao.impl.ProductsDaoImpl;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet(urlPatterns = "/DeleteProductServlet")
public class DeleteProductServlet extends HttpServlet {


    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8"); // 如果需要处理其他表单数据，这里可能是必要的

        // 从请求中获取产品ID
        String productIdStr = request.getParameter("id");
        System.out.println(productIdStr);
        if (productIdStr == null || productIdStr.isEmpty()) {
            // 如果产品ID为空，返回错误
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "缺少产品ID参数");
            return;
        }

        try {
            int productId = Integer.parseInt(productIdStr);
            ProductsDao productsDao = new ProductsDaoImpl(); // 假设ProductsDaoImpl是包含DeleteProduct方法的类
            String message = productsDao.DeleteProduct(productId); // 调用删除方法并获取返回的消息

            // 设置响应的内容类型为纯文本
            response.setContentType("text/plain");
            response.setCharacterEncoding("UTF-8");

            // 将消息写入响应体
            response.getWriter().write(message);

        } catch (NumberFormatException e) {
            // 如果ID不是有效的整数，返回错误
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "产品ID必须是一个有效的整数");
        }
    }
}
